using System.Text.Json;

namespace WeatherSDK;

/// <summary>
/// 道农云天气接口
/// </summary>
public class DdcEnvChinaWeatherProvider : BaseApiProvider, IWeatherApi
{
    private class WeatherResponseDTO
    {
        public string Status { get; set; }
        public string Count { get; set; }
        public string Info { get; set; }
        public string InfoCode { get; set; }
        public List<LiveData> Lives { get; set; }
    }

    private class LiveData
    {
        public string Province { get; set; }
        public string City { get; set; }
        public string Adcode { get; set; }
        public string Weather { get; set; }
        public string Temperature { get; set; }
        public string WindDirection { get; set; }
        public string WindPower { get; set; }
        public string Humidity { get; set; }
        public string ReportTime { get; set; }
        public float TemperatureFloat { get; set; }
        public float HumidityFloat { get; set; }
    }

    /// <summary>
    /// 道农只能云地址
    /// </summary>
    private const string HOST = "https://ddc.envchina.com/";

    private readonly HttpClient _httpClient;

    public DdcEnvChinaWeatherProvider()
    {
        var host = ReadConfig("DdcEnvChina:Host");
        if (string.IsNullOrEmpty(host))
        {
            host = HOST;
        }

        _httpClient = new HttpClient()
        {
            BaseAddress = new Uri(host),
            Timeout = TimeSpan.FromSeconds(Timeout),
        };
    }

    public async Task<LiveWeatherDTO> GetLive(string location)
    {
        var url = $"api/weather?adcode={location}";
        var response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        var responseJson = await response.Content.ReadAsStringAsync();
        var responseDto = JsonSerializer.Deserialize<WeatherResponseDTO>(responseJson, GetJsonSerializerOptions());
        if (responseDto != null && responseDto.Lives != null && responseDto.Lives.Count > 0)
        {
            var liveData = responseDto.Lives[0];

            var reportTime = Convert.ToDateTime(liveData.ReportTime);
            return new()
            {
                Province = liveData.Province,
                City = liveData.City,
                Adcode = liveData.Adcode,
                Weather = liveData.Weather,
                Temperature = liveData.Temperature,
                WindDirection = liveData.WindDirection,
                WindPower = liveData.WindPower,
                Humidity = liveData.Humidity,
                ReportTime = reportTime
            };
        }

        return null;
    }
}